package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import pojo.Warehouse;
import util.DBUtil;
import dao.WarehouseDao;

public class WarehouseDaoImpl implements WarehouseDao {

	Connection conn;
	PreparedStatement ps;

	private Connection getConnection() {
		try {
			InitialContext cxt = new InitialContext();// / JNDI 树
			DataSource ds = (DataSource) cxt
					.lookup("java:/comp/env/jdbc/myoracle");// // 查找 [tomcat
															// 协议]/jdbc/xxxx
			Connection conn = ds.getConnection();
			// System.out.println(conn);
			return conn;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
//		return DBUtil.createConnection();
	}

	@Override
	public List<Warehouse> findAll() {
		conn = getConnection();
		List<Warehouse> list = new ArrayList<Warehouse>();
		String sql = "select * from warehouse";
		try {
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql);

			ResultSet set = ps.executeQuery();
			while (set.next()) {
				Warehouse book = new Warehouse();
				book.setId(set.getString("id"));
				book.setAddr(set.getString("addr"));
				list.add(book);
			}
			conn.commit();
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			return list;
		}
	}

	@Override
	public int addWarehouse(Warehouse w) {
		conn = getConnection();
		String sql = "insert into warehouse(id, addr) values(?,?)";
		try {
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sql);

			if(w.getId()==null)
				w.setId(UUID.randomUUID().toString());
			ps.setString(1, w.getId());
			ps.setString(2, w.getAddr());

			int m = ps.executeUpdate();
			conn.commit();
			ps.close();
			conn.close();
			return m;
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
				ps.close();
				conn.close();
				return 0;
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				return 0;
			}
		}
	}
}
